package com.yanqu.road.server.manger.activity.liondance;

import com.yanqu.road.dao.impl.activity.liondance.LionDanceConfigDaoImpl;
import com.yanqu.road.dao.impl.activity.liondance.LionDanceUserApplyDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.climbtower.ClimbTowerConfig;
import com.yanqu.road.entity.activity.liondance.LionDanceConfig;
import com.yanqu.road.entity.activity.liondance.LionDanceUserApplyData;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.pb.activity.LionDanceProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.climbtower.ClimbTowerModule;
import com.yanqu.road.server.gameplayer.module.activity.liondance.LionDanceModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LionDanceMgr extends TempMgr {

    private static LionDanceConfig config;

    //缓存全服进度, 玩家登录时，更新
    //activityId, value
    private static Map<Integer, LionDanceMakeProcess> cacheAllMakeNumMap = new ConcurrentHashMap<>();

    //userId
    private static Map<Long, List<LionDanceUserApplyData>> applyDataListMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        ActivityInfo activityInfo = LionDanceMgr.getActivityInfo();
        if(ActivityMgr.activityInShowTime(activityInfo)){
            applyDataListMap = new LionDanceUserApplyDataDaoImpl().getLionDanceUserApplyData(activityInfo.getActivityId());
        }else {
            applyDataListMap = new ConcurrentHashMap<>();
        }
        return true;
    }

    @Override
    public boolean save() {
        if(applyDataListMap != null){
            for (Map.Entry<Long, List<LionDanceUserApplyData>> entry : applyDataListMap.entrySet()) {
                List<LionDanceUserApplyData> list = entry.getValue();
                for (int i = 0; i < list.size(); i++) {
                    LionDanceUserApplyData applyData = list.get(i);
                    if(applyData.isInsertOption()){
                        new LionDanceUserApplyDataDaoImpl().add(applyData);
                    }else if(applyData.isUpdateOption()){
                        new LionDanceUserApplyDataDaoImpl().update(applyData);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }


    public static void reloadActivityData() {
        int oldActivityId = 0;
        if(config != null){
            oldActivityId = config.getActivityInfo().getActivityId();
        }
        getLogger().info("reload LionDance Activity start");
        ActivityInfo tempActivityInfo;
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.LionDance.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no LionDance Activity in show time");
            config = null;
            applyDataListMap = new ConcurrentHashMap<>();
        } else {
            tempActivityInfo = openActivityInfoList.get(0);
            int tmpActivityId = tempActivityInfo.getActivityId();

            LionDanceConfig configTemp  = new LionDanceConfig();
            configTemp.setActivityInfo(tempActivityInfo);

            //config配置
            Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);

            LionDanceConfigDaoImpl dao = new LionDanceConfigDaoImpl();
            configTemp.setCombInfoList(dao.getLionDanceCombInfoList(tmpActivityId));
            configTemp.setCardInfoList(dao.getLionDanceCardInfoList(tmpActivityId));
            configTemp.setJumpConfigInfoList(dao.getLionDancePassConfigInfoList(tmpActivityId));

            configTemp.setConsumeItemId(activityConfigMap.get(eActivityConfigType.LIONDANCE_CONSUME_ITEM_ID.getName()).getIntValue());
            configTemp.setLIONDANCE_COLOR_REWARD_SCORE(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.LIONDANCE_COLOR_REWARD_SCORE.getName()).getValue(), "\\|"));
            configTemp.setLIONDANCE_COLOR_WEIGHT(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.LIONDANCE_COLOR_WEIGHT.getName()).getValue(), "\\|"));
            configTemp.setLIONDANCE_VALUE_ADD(activityConfigMap.get(eActivityConfigType.LIONDANCE_VALUE_ADD.getName()).getValue());
            configTemp.setLIONDANCE_COLOR_TIME(activityConfigMap.get(eActivityConfigType.LIONDANCE_COLOR_TIME.getName()).getIntValue());
            if(activityConfigMap.containsKey(eActivityConfigType.LIONDANCE_JUMP_SCORE.getName())){
                configTemp.setLIONDANCE_JUMP_SCORE(activityConfigMap.get(eActivityConfigType.LIONDANCE_JUMP_SCORE.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.LIONDANCE_ADD_ITEM_CONTINUED_TIME.getName())){
                configTemp.setLIONDANCE_ADD_ITEM_CONTINUED_TIME(activityConfigMap.get(eActivityConfigType.LIONDANCE_ADD_ITEM_CONTINUED_TIME.getName()).getIntValue());
            }
            config = configTemp;
            if(oldActivityId != tmpActivityId && oldActivityId != 0){
                applyDataListMap = new ConcurrentHashMap<>();
            }
        }

        getLogger().info("reload LionDance Activity finish");

        // 在线玩家下发数据
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            LionDanceModule module = gamePlayer.getModule(LionDanceModule.class);
            module.syncConfig();
            module.initUserData();
            module.syncUserData();
        }

    }
    public static LionDanceConfig getConfig() {
        return config;
    }

    public static ActivityInfo getActivityInfo() {
        if(config == null) {
            return null;
        }
        return config.getActivityInfo();
    }

    public static Map<Integer, LionDanceMakeProcess> getCacheAllMakeNumMap() {
        return cacheAllMakeNumMap;
    }

    public static void setCacheAllMakeNumMap(Map<Integer, LionDanceMakeProcess> cacheAllMakeNumMap) {
        LionDanceMgr.cacheAllMakeNumMap = cacheAllMakeNumMap;
    }

    public static int getActivityId(){
        if(getActivityInfo() == null){
            return 0;
        }
        return getActivityInfo().getActivityId();
    }

    public static List<LionDanceUserApplyData> getApplyDataList(long userId) {
        synchronized (applyDataListMap){
            if(!applyDataListMap.containsKey(userId)){
                applyDataListMap.put(userId, new ArrayList<>());
            }
        }
        return applyDataListMap.get(userId);
    }

    public static int giveCard(long userId, long toUserId, int applyNo, int cardId, UserBaseInfo userBaseInfo){
        List<LionDanceUserApplyData> toApplyList = getApplyDataList(toUserId);
        synchronized (toApplyList){
            LionDanceUserApplyData applyData = find(toApplyList, applyNo);
            if(applyData == null || (applyData.getApplyGoodsId() != cardId)){
                //申请不存在
                return GameErrorCode.E_LION_DANCE_APPLY_NO_VALID;
            }
            checkApplyDataTimeout(applyData);
            if(applyData.getStatus() != 0){
                return GameErrorCode.E_LION_DANCE_APPLY_NO_VALID;
            }
            applyData.setStatus(2);
            applyData.setFriendId(userId);
            applyData.setFriend(userBaseInfo);
        }
        return 0;
    }

    public static LionDanceUserApplyData find(List<LionDanceUserApplyData> applyDataList, int applyNo){
        for (LionDanceUserApplyData applyData : applyDataList) {
            if(applyData.getApplyNo() == applyNo){
                return applyData;
            }
        }
        return null;
    }

    public static int getMakeLionAddition(int makeNum, int process, LionDanceConfig config) {
        int totalProcess = makeNum * 1000 + process;
        List<String> list = StringUtils.stringToStringList(config.getLIONDANCE_VALUE_ADD(), "\\|");
        int add = 0;
        for (String str : list) {
            List<Integer> itemList = StringUtils.stringToIntegerList(str, ";");
            if(totalProcess >= itemList.get(0)){
                add = itemList.get(1);
            }
        }
        return add;
    }

    public static void checkApplyDataTimeout(LionDanceUserApplyData applyData) {

    }

    public static void getCrossAllMakeProcess(){
        if(config == null){
            return;
        }
        if(ActivityMgr.activityOverTime(config.getActivityInfo())){
           return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        if(cacheAllMakeNumMap.containsKey(activityInfo.getActivityId())){
            return;
        }

        LionDanceProto.CrossLionDanceGetAllMakeNumMgs.Builder crossSync = LionDanceProto.CrossLionDanceGetAllMakeNumMgs.newBuilder();
        crossSync.setActivityId(activityInfo.getActivityId());
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_LION_DANCE_GET_ALL_MAKE_NUM, crossSync));
    }

    public static void userLeaveUnion(long userId){
        List<LionDanceUserApplyData> applyDataList = applyDataListMap.get(userId);
        if(applyDataList != null){
            synchronized (applyDataList){
                for (LionDanceUserApplyData applyData : applyDataList) {
                    if(applyData.getStatus() == 0 && applyData.getFromType() == 1){
                        applyData.setStatus(4);
                        //上跨服取消
                        LionDanceProto.CrossLionDanceCancelApplyCardReqMsg.Builder crossMsg = LionDanceProto.CrossLionDanceCancelApplyCardReqMsg.newBuilder();
                        crossMsg.setActivityId(applyData.getActivityId());
                        crossMsg.setApplyNo(applyData.getApplyNo());
                        crossMsg.setApplyUserId(applyData.getUserId());
                        GamePlayerMgr.sendPacket(applyData.getUserId(), YanQuMessageUtils.buildMessage(Protocol.C_LION_DANCE_CANCEL_APPLY_CARD, crossMsg));
                    }
                }
            }
        }
    }
}
